import json
from itertools import product as itertools_product
from handle.S2Redis import redis_client, sync_data_background
from object.models import Logisticsvendors
from object.database import db
from handle.logger import logger
from config import Config

def get_providers_list():
    data=json.loads(redis_client.get('logisticsvendors'))
    for index,item in enumerate(data):
        if item['Remarks']==None:
            data[index]['Remarks']=''
    return data

def create_newprovider(data):
    # {
    #   "VendorName": "顺丰速运",
    #   "ContactNumber": "123-456-7890",
    #   "Address": "深圳市南山区科技园",
    #   "Country": "中国",
    #   "Remarks": "国内主要物流供应商"
    # }
    try:
        logisticsvendors = Logisticsvendors(
            VendorName=data['VendorName'],
            ContactNumber=data['ContactNumber'],
            Address=data['Address'],
            Country=data['Country'],
            Remarks=data['Remarks']
        ) 
        db.session.add(logisticsvendors)
        db.session.commit()
        data['VendorID']=logisticsvendors.VendorID
        sync_data_background()
        return data
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise
    
def update_provider_byid(data):
    try:
        logisticsvendors = Logisticsvendors.query.filter_by(VendorID=data['VendorID']).all()[0]
        logisticsvendors.VendorName=data['VendorName']
        logisticsvendors.ContactNumber=data['ContactNumber']
        logisticsvendors.Address=data['Address']
        logisticsvendors.Country=data['Country']
        logisticsvendors.Remarks=data['Remarks']
        db.session.commit()
        data['VendorID']=logisticsvendors.VendorID
        sync_data_background()
        return data
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise  
  
def del_provider_byid(VendorID):
    try:
        logisticsvendors = Logisticsvendors.query.filter_by(VendorID=VendorID).all()[0]
        db.session.delete(logisticsvendors)
        db.session.commit()
        sync_data_background()
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise  
  
    